package com.gxa.uhome.util;

import org.apache.poi.hssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

public class ExportUtil {
// 先从request域中获取数据
    /*
    本方法用来得到excel文件  list为查处的结果集合，headers为excel文件的中文列名名字数组，
    headers1为结果集的key的集合 顺序和header的中文顺序对应，

     */
        public  static HSSFWorkbook export(List<Map<String,Object>> list, String[] headers, String[] headrs1,String fileName,   HttpServletResponse response ) throws Exception {
            HSSFWorkbook workbook = new HSSFWorkbook();
           HSSFSheet sheet = workbook.createSheet(fileName);
            // headers表示excel表中第一行的表头 在excel表中添加表头
            HSSFRow row = sheet.createRow(0);
         for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
         }

        //准备将时间格式处理为标准日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 添加数据行:



            int column = 0;
            int rowNum = 1;

            for (Map<String, Object> map1 : list) {
                HSSFRow dataRow = sheet.createRow(rowNum);
                rowNum++;
                for (String s : headrs1) {
                    Object o = map1.get(s);
                    if (o instanceof String){
                        String value = (String)o;
                        dataRow.createCell(column).setCellValue(value);
                    }else  if (o instanceof Integer){
                        Integer value = (Integer)o;
                        dataRow.createCell(column).setCellValue(value);
                    }else  if (o instanceof Double){
                        Double value = (Double) o;
                        System.out.println(value);
                        dataRow.createCell(column).setCellValue(value);
                    }else if (o instanceof  Timestamp){
                        Date d = new Date(((Timestamp)o).getTime());
                        System.out.println(d);
                        dataRow.createCell(column).setCellValue(dateFormat.format(d));
                    }
                    column++;
                }

                column=0;
            }
                if (sheet==null){
                    throw  new Exception("创建表格失败");
                }
        //
            return workbook;
        }


}
